<!--
 * FilePath     : \src\views\scheduling\schedulingTable.vue
 * Author       : 苏军志
 * Date         : 2023-08-24 15:42
 * LastEditors  : 苏军志
 * LastEditTime : 2025-03-12 17:49
 * Description  : 排班表
 * CodeIterationRecord:
-->
<template>
  <div class="univer-sheet-wrap" ref="univerSheetWrapRef">
    <univer-sheet ref="univerSheetRef" v-if="templateData" :data="templateData" :config="config"></univer-sheet>
  </div>
</template>

<script setup lang="ts">
import type { sheetParamType } from "@/components/univerSheet/types/sheetParamType";
import type { configType } from "@/components/univerSheet/types/configType";
import { menuEnum } from "@/components/univerSheet/types/menuEnum";
import { useSchedulingControl } from "./hooks/useSchedulingControl";
import type { schedulingTableParam } from "./types/schedulingTableParam";
import { useSchedulingUniverUtil } from "./hooks/useSchedulingUniverUtil";
import { useUniverSheetTemplate } from "./hooks/useUniverSheetTemplate";
import { useSchedulingStatistics } from "./hooks/useSchedulingStatistics";
import { useDatas } from "./hooks/useDatas";
import { debounce } from "lodash-es";
const shiftSchedulingTable = ref<TableView>(useDatas().getShiftSchedulingDatas() as any);
const {
  readonly,
  month,
  schedulingType,
  shiftSchedulingRecordIDs,
  noonList,
  departmentPostList,
  shiftSchedulingMarkList,
  restrictCapabilityLevel,
  oneScreenDisplay,
  restMap,
  noonDutyMarkID,
  dailyStatisticsPostCondition,
  monthlyStatisticsPostCondition,
  shiftSchedulingStatisticsTable,
  employeeRemainingRestDaysDict,
  schedulingTemplateList
} = toRefs(useDatas().getTableParams());
const { getStatisticsMonthlyData, getStatisticsMonthlyColumn } = useSchedulingStatistics();
const { getEmployeeSecondmentNoon, canScheduling, checkSeconded } = useSchedulingControl(shiftSchedulingTable.value);
const monthlyStatisticsColumns = getStatisticsMonthlyColumn(monthlyStatisticsPostCondition.value);
const univerSheetWrapRef = ref<any>();
const univerSheetRef = ref<any>();
const sheet = ref<any>();
const templateData = ref<Record<string, any> | undefined>();
const config = ref<Record<string, any>>({});
const headerRowCount: number = 2;
const columnCount = shiftSchedulingTable.value.columns.length;
let rowCount: number = 0;
let statisticsStartRow: number = 0;
let initConfig: configType = {
  showHeader: !readonly.value,
  showFormula: false,
  showFooter: false,
  headerRowCount: headerRowCount,
  showRowIndexEnd: shiftSchedulingTable.value.rows.length + 1,
  headerFontColor: "#000000",
  headerBackgroundColor: "#ffef99",
  showMenuList: [menuEnum.CLEAR_CONTENT],
  onBeforeCellDataChange: (cellRange: Record<string, number>, cellData: Record<string, any>) => checkCellChange(cellRange, cellData),
  onCellDataChange: (cellRange: Record<string, number>, cellData: Record<string, any>) => changeSchedulingData(cellRange, cellData),
  onCellHover: (rowIndex: number, columnIndex: number) => showTip(rowIndex, columnIndex)
};
const { initUniverConfig, tableConvertCellData, setStudentScheduling, getCellData, getSecondBackGroundColor } = useSchedulingUniverUtil(
  initConfig,
  shiftSchedulingTable,
  false,
  restrictCapabilityLevel.value,
  (params: Record<string, any>) => openRemarkEdit(params),
  (templateID: string) => selectTemplate(templateID)
);
onMounted(() => init());
let columnWidth: number = 0;
/**
 * @description: 初始化
 */
const init = () => {
  const configParams = {
    maxColumnCount: columnCount,
    noonList: noonList.value,
    departmentPostList: departmentPostList.value,
    shiftSchedulingMarkList: shiftSchedulingMarkList.value,
    schedulingTemplateList: schedulingTemplateList.value
  };
  // 初始化Univer表格配置参数
  config.value = initUniverConfig(configParams);
  getTemplateData();
  // univer组件渲染完执行
  nextTick(() => {
    univerSheetRef.value?.setCrosshairHighlightColor("#08c979", 0.25);
    sheet.value = univerSheetRef.value?.univerAPI?.getActiveWorkbook().getActiveSheet();
    // 设置特殊逻辑渲染：备注、列特殊说明、历史日期标题颜色变淡、周日分割线
    setSpecialLogicRender(true);
    // 设置只读区域
    setReadonlyRanges();
    // 设置日统计行高
    sheet.value?.setRowHeightsForced(statisticsStartRow, dailyStatisticsPostCondition.value.length, 20);
    computeDailyStatistics();
  });
};
const getTemplateData = async () => {
  statisticsStartRow = shiftSchedulingTable.value.rows.length + headerRowCount;
  rowCount = statisticsStartRow + (dailyStatisticsPostCondition.value.length || 0);
  // 设置合并单元格数据，标题人员和统计列
  let mergeData = [
    { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 },
    { startRow: statisticsStartRow, startColumn: 0, endRow: rowCount - 1, endColumn: 0 }
  ];
  const cellData = tableConvertCellData(rowCount, columnCount, noonList.value, (rowIndex: number, columnIndex: number) =>
    getRestDay(rowIndex, columnIndex)
  );
  const univerSheetWidth = univerSheetWrapRef.value.clientWidth;
  // 排除宽度，40：行标列宽；40：层级列宽；60：姓名列宽
  const excludeWidth = 40 + 40 + 60;
  // 动态获取(表格宽度 - excludeWidth)/ 表格最大列数 - 2(层级列和姓名列)
  columnWidth = (univerSheetWidth - excludeWidth) / (columnCount - 1.5);
  // 如果设置的不是一屏显示完且动态算的列宽小于最小宽度，取最小宽度
  if (!oneScreenDisplay.value && columnWidth < 60) {
    columnWidth = 60;
  }
  // univerSheet模板需要的参数
  let params: sheetParamType = {
    rowCount: rowCount,
    columnCount: columnCount,
    maxColumnCount: columnCount,
    headerRowCount: headerRowCount,
    defaultRowHeight: 40,
    defaultColumnWidth: columnWidth,
    headerBackgroundColor: initConfig.headerBackgroundColor,
    headerFontColor: initConfig.headerFontColor,
    cellData: cellData,
    mergeData: mergeData
  };
  templateData.value = useUniverSheetTemplate().getShiftSchedulingSheet(params);
};
/**
 * @description: 设置只读区域
 */
const setReadonlyRanges = (clearFlag?: boolean) => {
  let readonlyRanges: Record<string, number>[] = [];
  // 排班表  全部只读
  if (readonly.value) {
    readonlyRanges.push({ startRow: 0, startColumn: 0, endRow: rowCount - 1, endColumn: columnCount - 1, canMoveRow: 0 });
  } else {
    // 标题行
    readonlyRanges.push({ startRow: 0, startColumn: 0, endRow: headerRowCount - 1, endColumn: columnCount - 1, canMoveRow: 0 });
    // 人员列
    readonlyRanges.push({ startRow: 0, startColumn: 0, endRow: rowCount - 1, endColumn: 1, canMoveRow: 1 });
    // 日统计行
    readonlyRanges.push({
      startRow: statisticsStartRow,
      startColumn: 0,
      endRow: rowCount - 1,
      endColumn: columnCount - 1,
      canMoveRow: 0
    });
    let secondRanges: Record<string, number>[] = [];
    let transferRanges: Record<string, number>[] = [];
    shiftSchedulingTable.value.rows.forEach((row, rowIndex) => {
      shiftSchedulingTable.value.columns.forEach((column, columnIndex) => {
        // 借调被借调
        if (checkSeconded(rowIndex, columnIndex)) {
          secondRanges.push({
            startRow: rowIndex + headerRowCount,
            startColumn: columnIndex,
            endRow: rowIndex + headerRowCount,
            endColumn: columnIndex,
            canMoveRow: 1
          });
        }
        // 转科前排班数据
        if (row.employee.transferDate && column.key === datetimeUtil.formatDate(row.employee.transferDate, "yyyyMMdd")) {
          transferRanges.push({
            startRow: rowIndex + headerRowCount,
            startColumn: 2,
            endRow: rowIndex + headerRowCount,
            endColumn: columnIndex
          });
        }
      });
    });
    if (secondRanges.length) {
      readonlyRanges = [...readonlyRanges, ...secondRanges, ...transferRanges];
    }
  }
  univerSheetRef.value.setReadonlyRanges(readonlyRanges, clearFlag);
  // 修复滚动条遮挡数据
  univerSheetRef.value.fixScrollBarPressData();
};
/**
 * @description: 检查单元格更改
 * @param cellRange
 * @param cellData
 * @return
 */
const checkCellChange = (cellRange: Record<string, number>, cellData: Record<string, any>) => {
  let isStatistics = false;
  if (cellRange.startRow >= statisticsStartRow) {
    isStatistics = true;
  }
  if (isStatistics) {
    // 当普通单元格拖拉到统计列时
    const style = cellData[cellRange.startRow][cellRange.startColumn].s;
    if (typeof style === "string" && (style.includes("statistics-cell-style") || style.includes("header-cell-style"))) {
      return true;
    }
    return false;
  }
  return undefined;
};
/**
 * @description: 排班表发生改变
 *               数据发生变化时，会触发两次，第一次删除，第二次新增；
 *               数据删除时只触发一次删除；
 *               所以这里使用防抖，只执行最后一次，防止死循环
 * @param cellValue
 * @param cellData
 * @return
 */
const changeSchedulingData = debounce(async (cellRange: Record<string, number>, cellData: Record<string, any>) => {
  const { startRow, startColumn, endRow, endColumn } = cellRange;
  for (let index = startRow; index <= endRow; index++) {
    let rowIndex = index - headerRowCount;
    const employeeID = shiftSchedulingTable.value.rows[rowIndex]?.employee?.employeeID;
    if (!employeeID) {
      return;
    }
    for (let columnIndex = startColumn; columnIndex <= endColumn; columnIndex++) {
      const column: TableColumn | undefined = shiftSchedulingTable.value.columns.find((column) => column.index === columnIndex);
      if (!column) {
        return;
      }
      const columnData = cellData[index]?.[columnIndex];
      // 如果是拖拽复制，可能是借调/被借调半天的单元格，特殊处理
      if (!columnData.custom) {
        columnData.custom = {};
      }
      columnData.custom.noonPost = await deelSecondmentCellData(rowIndex, columnIndex, column.key, columnData);
      const oldData = common.clone(shiftSchedulingTable.value.rows[rowIndex][column.key]);
      const oldRemarkMark = oldData.markList.find((mark: any) => mark.markID === 147);
      const newRemarkMark = columnData.custom.markList?.find((mark: any) => mark.markID === 147);
      shiftSchedulingTable.value.rows[rowIndex][column.key].employeeID = employeeID;
      shiftSchedulingTable.value.rows[rowIndex][column.key].noonPost = columnData.custom.noonPost;
      shiftSchedulingTable.value.rows[rowIndex][column.key].markList = columnData.custom.markList;
      shiftSchedulingTable.value.rows[rowIndex][column.key].schedulingDate = column.value;
      const range = sheet.value.getRange(index, columnIndex, 1, 1);
      // 如果原来有备注，删除
      if (oldRemarkMark) {
        await range.clearComment();
      }
      // 如果新的有备注，新增
      if (newRemarkMark) {
        await range.addComment({ dataStream: newRemarkMark.markValue + "\r\n" });
      }
      // 如果是删除，要处理背景色，岗位和标记的背景删除，保留借调/被借调背景
      if (
        ((oldData?.noonPost && Object.keys(oldData?.noonPost).length) || oldData?.markList?.length || !oldData.schedulingDate) &&
        (!columnData?.custom?.noonPost || (!Object.keys(columnData?.custom?.noonPost).length && !columnData?.custom?.markList?.length))
      ) {
        const backgroundColor = getSecondBackGroundColor(
          shiftSchedulingTable.value.rows[rowIndex],
          shiftSchedulingTable.value.rows[rowIndex][column.key]
        );
        if (!backgroundColor) {
          range.setBackgroundColor("#ffffff");
        }
      }
      // 同步设置带教学生排班
      setStudentScheduling(columnData, range, sheet.value);
    }
  }
  triggerShiftSchedulingChange();
  nextTick(() => triggerShiftSchedulingChange(startRow, endRow));
}, 0);
/**
 * @description: 触发排班改变的逻辑
 * @param startRow
 * @param endRow
 * @return
 */
const triggerShiftSchedulingChange = (startRow?: number, endRow?: number) => {
  // emits("shiftSchedulingChange", () => {
  //   nextTick(async () => {
  //     if (startRow && endRow) {
  //       // 设置休假天数
  //       await setRestDay(startRow, endRow);
  //     }
  //     // 计算日统计
  //     await computeDailyStatistics();
  //     // 如果是周排班计算月统计
  //     if (schedulingType.value === schedulingTypeWeek) {
  //       await computeMonthlyStatistics();
  //     }
  //   });
  // });
};
/**
 * @description: 处理拖拽复制时经过的半天借调/被借单元格
 * @param rowIndex
 * @param columnIndex
 * @param columnKey
 * @param columnData
 * @return
 */
const deelSecondmentCellData = async (rowIndex: number, columnIndex: number, columnKey: string, columnData: Record<string, any>) => {
  const employeeSecondmentNoon = getEmployeeSecondmentNoon(rowIndex, columnIndex);
  const noonPost = columnData?.custom?.noonPost || {};
  // 不是借调/被借单元格，直接返回
  if (!employeeSecondmentNoon[0]) {
    return noonPost;
  }
  const oldNoonPost = shiftSchedulingTable.value.rows[rowIndex][columnKey].noonPost || {};
  let newNoonPost: Record<string, Record<string, any>> = {};
  noonList.value.forEach((noon: Record<string, any>) => {
    const flag = canScheduling(employeeSecondmentNoon, noon.value);
    newNoonPost[noon.value] = flag ? noonPost[noon.value] : oldNoonPost[noon.value];
  });
  const backgroundColor = getSecondBackGroundColor(
    shiftSchedulingTable.value.rows[rowIndex],
    shiftSchedulingTable.value.rows[rowIndex][columnKey]
  );
  const isSunday = shiftSchedulingTable.value.columns[columnIndex]?.isSunday;
  let newValue: Record<string, any> = getCellData(
    newNoonPost,
    columnData?.custom?.markList,
    noonList.value,
    undefined,
    backgroundColor,
    isSunday
  );
  nextTick(async () => {
    await sheet?.value.getRange(rowIndex + headerRowCount, columnIndex, 1, 1).setValue(newValue);
  });
  return newNoonPost;
};

/**
 * @description: 计算日统计
 * @return
 */
const computeDailyStatistics = async () => {
  if (!dailyStatisticsPostCondition.value.length) {
    return;
  }
  const { rows, columns } = shiftSchedulingTable.value;
  let statisticsValues: Record<string, any>[][] = [];
  dailyStatisticsPostCondition.value.forEach((postCondition:any) => {
    let rowValues: Record<string, any>[] = [];
    columns.forEach((column: any, index: number) => {
      // 合计列
      if (index === 0) {
        rowValues.push({ v: "合计", s: "statistics-cell-style" });
        return;
      }
      // 条件列
      if (index === 1) {
        rowValues.push({ v: postCondition.conditionKey, s: "statistics-cell-style" });
        return;
      }
      let sum: number = 0;
      rows.forEach((row, rowIndex) => {
        const noonPost = row[column.key]?.noonPost;
        // 空值检查
        if (!noonPost) {
          return;
        }
        let employeeSecondmentNoon = getEmployeeSecondmentNoon(rowIndex, index);
        for (const noonType in noonPost) {
          if (
            canScheduling(employeeSecondmentNoon, noonType) &&
            postCondition.conditionValue.includes(noonPost[noonType].departmentPostID)
          ) {
            sum += 0.5;
          }
        }
      });
      rowValues.push({ v: sum, s: "statistics-cell-style" });
    });
    statisticsValues.push(rowValues);
  });
  await sheet.value
    ?.getRange(statisticsStartRow, 0, dailyStatisticsPostCondition.value.length, shiftSchedulingTable.value.columns.length)
    .setValues(statisticsValues);
};

/**
 * @description: 计算月统计
 */
const computeMonthlyStatistics = async () => {
  const monthlyStatisticsData = getStatisticsMonthlyData(
    month.value,
    shiftSchedulingStatisticsTable.value,
    employeeRemainingRestDaysDict.value,
    monthlyStatisticsPostCondition.value,
    noonDutyMarkID.value
  );
  if (!monthlyStatisticsData?.length) {
    return;
  }
  let statisticsValues: Record<string, any>[][] = [];
  let statisticsTitleData: Record<string, any>[][] = [[], []];
  shiftSchedulingTable.value.rows.forEach((row) => {
    const rowData = monthlyStatisticsData.find((data) => data.employeeID === row.employee.employeeID) || {};
    let rowValues: Record<string, any>[] = [];
    monthlyStatisticsColumns.forEach((statisticsColumn, index) => {
      if (!statisticsTitleData[0][index]) {
        statisticsTitleData[0][index] = { v: `排班岗位月统计（${month.value}月）`, s: "header-cell-style" };
      }
      if (!statisticsTitleData[1][index]) {
        statisticsTitleData[1][index] = { v: statisticsColumn.name, s: "header-cell-style" };
      }
      rowValues.push({ v: rowData[statisticsColumn.key], s: "monthly-statistics-cell-style" });
    });
    statisticsValues.push(rowValues);
  });
  statisticsValues = [...statisticsTitleData, ...statisticsValues];
  await sheet.value
    ?.getRange(0, shiftSchedulingTable.value.columns.length, statisticsStartRow, monthlyStatisticsColumns.length)
    .setValues(statisticsValues);
};
// #region 休假天数计算逻辑
/**
 * @description: 设置休假天数
 */
const setRestDay = async (startRow: number, endRow: number) => {
  for (let index = startRow; index <= endRow; index++) {
    let rowIndex = index - headerRowCount;
    shiftSchedulingTable.value.columns.forEach(async (column, columnIndex) => {
      // 跳过人员列
      if (columnIndex < 2) {
        return;
      }
      const cellData: Record<string, any> = shiftSchedulingTable.value.rows[rowIndex][column.key];
      // 跳过未排班
      // if (!cellData.noonPost || !Object.keys(cellData.noonPost).length) {
      //   return;
      // }
      const restDay = getRestDay(rowIndex, columnIndex);
      const backgroundColor = getSecondBackGroundColor(
        shiftSchedulingTable.value.rows[rowIndex],
        shiftSchedulingTable.value.rows[rowIndex][column.key]
      );
      const isSunday = shiftSchedulingTable.value.columns[columnIndex]?.isSunday;
      let newCellData: Record<string, any> = getCellData(
        cellData.noonPost,
        cellData.markList,
        noonList.value,
        restDay,
        backgroundColor,
        isSunday
      );
      await sheet?.value.getRange(index, columnIndex, 1, 1).setValue(newCellData);
    });
  }
};
/**
 * @description: 获取排班单元格本月第几天休息
 * @param row
 * @param columnKey
 * @return
 */
const getRestDay = (rowIndex: number, columnIndex: number) => {
  let restDay: number | undefined;
  const column: TableColumn | undefined = shiftSchedulingTable.value.columns.find((column) => column.index === columnIndex);
  if (!column) {
    return restDay;
  }
  if (!restMap.value?.size) {
    return restDay;
  }
  const employeeID = shiftSchedulingTable.value.rows[rowIndex]?.employee?.employeeID;
  if (!employeeID) {
    return restDay;
  }
  const map = restMap.value.get(employeeID);
  if (map?.size) {
    const counts: Record<string, number> = map.get(column.key) || {};
    restDay = counts.maternityCount || counts.annualCount || counts.count || undefined;
  }
  return restDay;
};
// #endregion

/**
 * @description: 设置特殊逻辑渲染
 * @param initRemarkFlag 是否初始化备注
 * @return
 */
const setSpecialLogicRender = (initRemarkFlag: boolean) => {
  shiftSchedulingTable.value.rows.forEach((row, rowIndex) => {
    shiftSchedulingTable.value.columns.forEach(async (column, columnIndex) => {
      // 初始化备注
      if (initRemarkFlag) {
        initCellRemark(rowIndex, columnIndex, column);
      }
      // 今天之前的列标题颜色变淡
      if (column.key < datetimeUtil.getNowDate("yyyyMMdd")) {
        sheet.value?.getRange(0, columnIndex, headerRowCount, 1).setBackgroundColor("#f4edcb");
      }
      // 有特殊说明的列标题字体颜色标记为红色
      if (column.specialContent) {
        sheet.value?.getRange(0, columnIndex, headerRowCount, 1).setFontColor("#ff0000");
      }
      // 设置标题的周日分割线
      setTitleSundayDivider(rowIndex, columnIndex, column);
    });
  });
};
/**
 * @description: 设置标题的周日分割线
 * @param rowIndex
 * @param columnIndex
 * @param column
 * @return
 */
const setTitleSundayDivider = async (rowIndex: number, columnIndex: number, column: TableColumn) => {
  if (!column.isSunday) {
    return;
  }
  for (let index = 0; index < headerRowCount; index++) {
    const sundayColumnRange = sheet.value?.getRange(index, columnIndex, 1, 1);
    if (sundayColumnRange) {
      const data = sundayColumnRange.getCellData();
      const style = common.clone(sundayColumnRange.getCellStyleData());
      style.bd.r.s = 13;
      data.s = style;
      nextTick(() => sundayColumnRange.setValue(data));
    }
  }
};

// #region 排班备注相关逻辑
/**
 * @description: 初始化单元格备注
 * @param rowIndex
 * @param columnIndex
 * @param column
 * @return
 */
const initCellRemark = (rowIndex: number, columnIndex: number, column: TableColumn) => {
  // 跳过人员列
  if (columnIndex < 2) {
    return;
  }
  const markList: Record<string, any>[] = shiftSchedulingTable.value.rows[rowIndex][column.key].markList;
  // 跳过无标记
  if (!markList?.length) {
    return;
  }
  const remark = markList.find((mark) => mark.markID === 147);
  // 没有备注 跳过
  if (!remark || !remark.markValue) {
    return;
  }
  const range = sheet?.value.getRange(rowIndex + headerRowCount, columnIndex, 1, 1);
  range.addComment({
    dataStream: remark.markValue + "\r\n",
    paragraphs: [{ startIndex: remark.markValue.length }],
    textRuns: []
  });
};

const remarkParams = ref<Record<string, any>>({});
/**
 * @description: 打开备注编辑框
 * @param params
 * @return
 */
const openRemarkEdit = (params: Record<string, any>) => {
  remarkParams.value = params;
  remarkParams.value.title = `${params.employeeName}${params.date}排班备注`;
  const markList: Record<string, any>[] =
    shiftSchedulingTable.value.rows[remarkParams.value.rowIndex][remarkParams.value.columnKey].markList;
  const remark = markList.find((mark) => mark.markID === remarkParams.value.markID);
  remarkParams.value.remark = remark?.markValue || "";
  remarkParams.value.show = true;
};
/**
 * @description: 设置备注
 */
const setCellRemark = async () => {
  const remarkMark = {
    markID: remarkParams.value.markID,
    markValue: remarkParams.value.remark
  };
  const range = sheet?.value.getRange(remarkParams.value.rowIndex + headerRowCount, remarkParams.value.columnIndex, 1, 1);
  const newComment = {
    dataStream: remarkMark.markValue + "\r\n",
    paragraphs: [{ startIndex: remarkMark.markValue.length }],
    textRuns: []
  };
  let markList: Record<string, any>[] =
    shiftSchedulingTable.value.rows[remarkParams.value.rowIndex][remarkParams.value.columnKey].markList || [];
  if (markList?.length) {
    const index = markList.findIndex((mark) => mark.markID === remarkParams.value.markID);
    if (index !== -1) {
      // 如果值为空移除备注
      if (!remarkParams.value.remark) {
        markList.splice(index, 1);
        await range.clearComment();
      } else {
        // 如果原来就有备注，更新，否则新增
        if (markList[index].markValue) {
          const comment = range.getComment();
          await comment?.update(newComment);
        } else {
          await range.addComment(newComment);
        }
        markList[index].markValue = remarkMark.markValue;
      }
    } else {
      markList.push(remarkMark);
      await range.addComment(newComment);
    }
  } else {
    markList.push(remarkMark);
    await range.addComment(newComment);
  }
  shiftSchedulingTable.value.rows[remarkParams.value.rowIndex][remarkParams.value.columnKey].markList = markList;
  remarkParams.value.show = false;
};
// #endregion

// #region 排班模板相关逻辑
const schedulingTemplateRef = ref<any>();
const showTemplateDialog = ref<boolean>(false);
const templateParams = ref<Record<string, any>>({ selectionMode: true });
const selectTemplate = (templateID: string) => {
  templateParams.value.noonList = noonList;
  templateParams.value.departmentPostList = departmentPostList;
  templateParams.value.shiftSchedulingMarkList = shiftSchedulingMarkList;
  templateParams.value.schedulingTemplateRecordID = templateID;
  showTemplateDialog.value = true;
};
/**
 * @description: 将排班摸模板数据应用到排班表
 */
const setTemplateData = () => {
  const range = sheet.value?.getActiveRange();
  if (!range) {
    return;
  }
  const { startRow, startColumn } = range.getRange();
  const cellDatas = schedulingTemplateRef.value.getSheetData();
  let newCellDatas: Record<number, Record<number, any>> = {};
  Object.keys(cellDatas).forEach((rowIndex) => {
    const newRowIndex = startRow + Number(rowIndex);
    // 大于排班表行数 跳过
    if (newRowIndex - headerRowCount >= shiftSchedulingTable.value.rows.length) {
      return;
    }
    const rowData = cellDatas[rowIndex];
    let newRowData: Record<number, any> = {};
    // 循环列
    Object.keys(rowData).forEach((columnIndex) => {
      const newColumnIndex = startColumn + Number(columnIndex);
      // 大于排班表列数 跳过
      if (newColumnIndex >= shiftSchedulingTable.value.columns.length) {
        return;
      }
      newRowData[newColumnIndex] = rowData[columnIndex];
    });
    newCellDatas[newRowIndex] = newRowData;
  });
  sheet?.value.getRange(startRow, startColumn, Object.keys(newCellDatas).length, Object.keys(newCellDatas).length).setValues(newCellDatas);
  showTemplateDialog.value = false;
};
// #endregion
/**
 * @description: 显示提示信息
 * @param rowIndex
 * @param columnIndex
 * @return
 */
const showTip = (rowIndex: number, columnIndex: number) => {
  // 跳过日统计行并关闭提示
  if (rowIndex >= statisticsStartRow) {
    univerSheetRef.value?.hiddenPopupMessage();
    return;
  }
  // 如果是标题行判断有没有特殊说明，有显示，没有返回
  if (rowIndex < headerRowCount && columnIndex < shiftSchedulingTable.value.columns.length) {
    const specialContent = shiftSchedulingTable.value.columns[columnIndex].specialContent;
    if (specialContent) {
      univerSheetRef.value?.showPopupMessage(rowIndex, columnIndex, specialContent);
    } else {
      univerSheetRef.value?.hiddenPopupMessage();
    }
    return;
  }
  // 跳过非人员列行并关闭提示
  if (columnIndex >= 2) {
    univerSheetRef.value?.hiddenPopupMessage();
    return;
  }
  const employee = shiftSchedulingTable.value.rows[rowIndex - headerRowCount].employee;
  // 没有提示信息 就不显示
  if (!employee.tipContent) {
    univerSheetRef.value?.hiddenPopupMessage();
    return;
  }
  univerSheetRef.value?.showPopupMessage(rowIndex, columnIndex, employee.tipContent);
};
// #region 撤销和恢复逻辑
// 建立shiftSchedulingTable快照，用于撤销、恢复操作
// const { undo, redo, canUndo, canRedo } = useDebouncedRefHistory(shiftSchedulingTable, { deep: true, debounce: 100 });
// const onUndo = () => {
//   console.log("onUndo");
//   if (canUndo) {
//     undo();
//     triggerUniver();
//   }
// };
// const onRedo = () => {
//   console.log("onRedo");
//   if (canRedo) {
//     redo();
//     triggerUniver();
//   }
// };
// const triggerUniver = () => {
//   const cellData = tableConvertCellData(rowCount, columnCount, noonList.value, (rowIndex: number, columnIndex: number) =>
//     getRestDay(rowIndex, columnIndex)
//   );
//   console.log("===", cellData);
//   sheet.value?.getRange(0, 0, rowCount, columnCount).setValues(cellData);
//   nextTick(() => triggerShiftSchedulingChange());
// };
// #endregion
</script>

<style lang="scss">
  .univer-sheet-wrap {
    height: 100%;
    width: 100%;
  }
</style>
